package com.dtkavin.threads.syn;

import java.util.Random;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

/**
 * Created by john on 10/4/16.
 * master发命令，之后3个slave执行，执行完后通知master执行
 */
public class CountDownLatchDemo {

    private static CountDownLatch order = new CountDownLatch(3);
    private static CountDownLatch signal = new CountDownLatch(1);

    public static void main(String[] args) {
        ExecutorService executorService = Executors.newFixedThreadPool(3);
        final Slave slave = new Slave();
        for (int i = 0; i < 3; i++) {
            executorService.execute(new Runnable() {
                public void run() {
                    slave.run();
                }
            });
        }
        Master master = new Master();
        master.run();
        executorService.shutdown();
    }

    static class Master {
        public void run() {
            try {
                Thread.sleep(2000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            System.out.println("master prepared " + Thread.currentThread().getName());
            signal.countDown();

            try {
                order.await();
                System.out.println("master collected all");
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    }

    static class Slave {
        public void run() {
            try {
                System.out.println("slave: " + Thread.currentThread().getName() + " prepared");
                signal.await();
                Thread.sleep(new Random().nextInt(5000));
                System.out.println("slave: " + Thread.currentThread().getName() + " done ");
                order.countDown();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    }
}
